package com.alibaba.csp.sentinel.dashboard.rule.nacos;

import com.alibaba.csp.sentinel.dashboard.rule.DynamicRuleProvider;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author marcher
 */
public abstract class AbstractRuleNacosProvider<T> implements DynamicRuleProvider<T> {

    @Resource
    private ConfigService configService;

    @Override
    public T getRules(String appName) throws Exception {
        return null;
    }

    /**
     * 从 Nacos 拉取规则配置
     *
     * @param appName   应用名称
     * @param clazz     规则类
     * @return
     * @throws NacosException
     */
    protected <T> List<T> getOriginRules(String appName, Class<T> clazz) throws NacosException {
        String dataId = buildDataId(appName);
        String rules = configService.getConfig(dataId, SentinelNacosConstants.GROUP_ID, SentinelNacosConstants.READ_TIMEOUT);
        if (StringUtil.isBlank(rules)) {
            return new ArrayList<>();
        }

        return SentinelNacosConvert.convertToRuleEntity(rules, clazz);
    }

    /**
     * 构建 dataId
     *
     * @param appName   appName
     * @return
     */
    private String buildDataId(String appName) {
        return appName + postfix();
    }

    /**
     * 后缀
     *
     * @return
     */
    abstract protected String postfix();
}
